﻿using System;
using System.IO;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using VSLangProj;

namespace Xiety.CompileGenerator
{
	public abstract class BaseCustomToolGenerator : BaseCodeGeneratorWithSite
	{
		private const string ProjectFullPathItem = "FullPath";
		private const string ProjectOutputPathItem = "OutputPath";

		protected abstract string Generate(string fname, string text);

		protected string GetCurrentProjectOutputPath()
		{
			var project = GetProject();
			var fullPath = project.Properties.Item(ProjectFullPathItem).Value.ToString();
			var outputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item(ProjectOutputPathItem).Value.ToString();

			return Path.Combine(fullPath, outputPath);
		}

		protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
		{
			return this
				.Try(t => t.Generate(inputFileName, inputFileContent))
				.Catch(ConvertException)
				.With(s => Encoding.UTF8.GetBytes(s));
		}

		private string ConvertException(Exception e)
		{
			var message = this.CreateExceptionMessage(e);
			this.GeneratorErrorCallback(false, 1, message, 0, 0);
			return null;
		}

		protected ProjectItem GetProjectItem()
		{
			return (ProjectItem)GetService(typeof(ProjectItem));
		}

		protected Project GetProject()
		{
			return GetProjectItem().ContainingProject;
		}

		protected VSProject GetVSProject()
		{
			return (VSProject)GetProject().Object;
		}
	}
}
